//
//  OAuthViewController.swift
//  DSWeibo
//
//  Created by J on 16/4/16.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    let WB_App_Key = "3714539610"
    let WB_App_Secret = "d23d1dcd6b6ba39feddb1409ba126604"
    let WB_App_redirect_url = "http://weibo.com/u/3106243403/home?wvr=5"

    //MARK: －懒加载
    private lazy var webView :UIWebView = {
        let webV = UIWebView()
        webV.delegate = self
        return webV
    }()

    
    override func loadView(){
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //0.初始化导航条
        navigationItem.title = "小码哥微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action:#selector(OAuthViewController.close))
        
        
        
        
        //1.获取未授权的RequestToken
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_App_redirect_url)"
        
        let url = NSURL(string:urlStr )
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)

        
    }
    
    
    ///  关闭界面
    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
}

extension OAuthViewController:UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        /*
        请求授权 https://api.weibo.com/oauth2/authorize?client_id=3714539610&redirect_uri=http://weibo.com/u/3106243403/home?wvr=5
        授权成功 http://weibo.com/u/3106243403/home?wvr=5&code=8acbdf77200aaa42ba5f67b628e6ccdb
        取消授权 http://weibo.com/u/3106243403/home?wvr=5&error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        */
        
        //1.判断是否是授权回调页,如果不是继续加载 因为除了请求授权页面不是WB_App_redirect_url 开头  授权失败和成功都是 WB_App_redirect_url开头
        if !request.URL!.absoluteString.hasPrefix(WB_App_redirect_url){
            return true
        }
        
        //2.判断是否授权成功  授权成功后的url包含code=
        let urlStr = request.URL!.query
        let codeStr = "code="
        let  range = urlStr!.rangeOfString(codeStr)
        if range != nil  {
            let code = urlStr!.substringFromIndex(range!.endIndex)//从code=后面开始截取
//            print(code)
            
        loadAccessToken(code)
        }else{//取消授权
        close()
  
        }
        
        return false
    }
    
    ///获取已经授权的ACCessToken
    private func loadAccessToken(code:String){
        /*
         同用户对同一应用授权多次 accessToken一直相同
         如果自己对自己用户授权有效期为5年差1天
         如果他人对我自己应用授权 有效期为三天
         1.定义路径
         */
    let path = "oauth2/access_token"
    //2.封装参数
        let parameters = ["client_id":WB_App_Key,"client_secret":WB_App_Secret,"grant_type":"authorization_code","code":code,"redirect_uri":WB_App_redirect_url]
        NetWorkTools.shareNetWorkTools().POST(path, parameters: parameters, success: { (NSURLSessionDataTask, result:AnyObject?) in
//            print(NSDate.init(timeIntervalSinceNow: 157679999))
            /*
             验证expires_in不是字符串
            let data =   try! NSJSONSerialization.dataWithJSONObject(result!, options: NSJSONWritingOptions.PrettyPrinted)
            let str = NSString(data: data, encoding: NSUTF8StringEncoding)
             2.00DoTN5DM8p4DE00a15deb62b4KnzB
             
             plist: 只能存储系统自带的数据类型 对象不能存
             将兑现转换为json之后写入文件
             偏好设置:本质plist
             归档:可以存储自定义对象
             数据库: 用于存储大数据, 特点效率高
             
             */
        let account = UserAccount.init(dic: result! as! [String : AnyObject])
            //归档模型
            account.saveArchiver()
            
            //获取用户信息
            account.loadUserInfo({ (account, error) in
                if account != nil {
                    account?.saveArchiver()//保存获取到的数据
                    //去欢迎界面
                    NSNotificationCenter.defaultCenter().postNotificationName(XMGSwitchRootViewControllerKey, object: false)
                
                }
                SVProgressHUD.showInfoWithStatus("网络不给力", mastType: SVProgressHUDMaskType.Black)

            })
            

        }) { (task:NSURLSessionDataTask?, error:NSError) in
            SVProgressHUD.showInfoWithStatus("网络不给力", mastType: SVProgressHUDMaskType.Black)
            print(error)
        }
    
   //3.
    
    }
  
    
    func webViewDidStartLoad(webView: UIWebView) {
        //正在加载...
        SVProgressHUD.showInfoWithStatus("正在加载...", mastType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //加载完毕
        SVProgressHUD.dismiss()

    }
    
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()

    }
    
}
